package middlewares

import (
	"strings"
	"xss/controllers"
	"xss/pkg/jwt"

	"github.com/gin-gonic/gin"
)

// JWTAuthMiddleware 基于JWT的认证中间件
func JWTAuthMiddleware(issuer string) func(c *gin.Context) {
	return func(c *gin.Context) {
		// 客户端携带Token有三种方式 1.放在请求头 2.放在请求体 3.放在URI
		// 这里假设Token放在Header的Authorization中，并使用Bearer开头
		// 这里的具体实现方式要依据你的实际业务情况决定
		authHeader := c.Request.Header.Get("Authorization")
		if authHeader == "" {
			controllers.RespErr(c, controllers.CodeNeedAuth)
			c.Abort()
			return
		}
		// 按空格分割
		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			controllers.RespErr(c, controllers.CodeInvalidToken)
			c.Abort()
			return
		}

		token := parts[1]
		mc, ok := jwt.IsValidToken(token, issuer)
		if !ok {
			controllers.RespErr(c, controllers.CodeInvalidToken)
			c.Abort()
		}
		// 将当前请求的username信息保存到请求的上下文c上
		c.Set(controllers.CtxUsernameKey, mc.Username)
		c.Set(controllers.CtxUserIDKey, mc.UserID)
		c.Set(controllers.CtxIsAdminKey, mc.Issuer == jwt.AdminIssuer)
		c.Next() // 后续的处理函数可以用过c.Get("username")来获取当前请求的用户信息
	}
}

//JWTAuthAdminMiddleware 效验管理员的token
func JWTAuthAdminMiddleware() func(c *gin.Context) {
	return JWTAuthMiddleware(jwt.AdminIssuer)
}

//JWTAuthUserMiddleware 效验用户的token
func JWTAuthUserMiddleware() func(c *gin.Context) {
	return JWTAuthMiddleware(jwt.UserIssuer)
}
